<template>
    <div class="flex flex-wrap items-center">
        <el-dropdown style="margin-top: 10px;">
            <el-button type="default" style=" padding-left: 20px;  padding-right: 20px; border-radius: 20px;">
                {{ cacheData.user.NAME }}
                <el-icon class="el-icon--right">
                    <arrow-down />
                </el-icon>
            </el-button>

            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item icon="Edit">修改密码</el-dropdown-item>
                    <el-dropdown-item @click="logout" icon="SwitchButton" >注销</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
</template>

<script  lang="ts" setup>
import { getCurrentInstance , onMounted, onBeforeUnmount } from 'vue'
import { getStore, removeStore } from '~/util/store';
import router from '~/router/router'
import axios from 'axios'

// 初始化系统缓存数据
let cacheData = getStore({ name: "CacheData" });
if (cacheData == null) {
    router.push("/login")
} else {
    cacheData.user.firstName = cacheData.user.NAME.substring(0, 1);
    cacheData.user.lastName = cacheData.user.NAME.substring(1);
}

// 定时刷新[每5分钟主动刷新一次，查看当前状态]
let timer = setInterval(() => {
    // 定时更新cacheDate
    cacheData = getStore({ name: "CacheData" });

    // 刷新用户登录状态
    axios.post('/api/index/user/refresh', {
        ticket: cacheData.ticket
    }).then(
        res => {
            if (res.data == null || !res.data.success) {
                gotoLogin();
            }
        }
    )

}, 60 * 1000 * 5)

// 注销
function logout() {
    // 调用logout的API
    cacheData = getStore({ name: "CacheData" });

    // 刷新用户登录状态
    axios.post('/api/index/user/logout', {
        ticket: cacheData.ticket
    }).then(
        res => {
            //if (res.data != null && res.data.success) {
            gotoLogin()
            //}
        }
    )
}

// 清理缓存，且前往登录界面
function gotoLogin(){
    clearInterval(timer);
    removeStore(
        {
            name: "CacheData",
            type: true
        }
    );
    router.push('/login')
}

// ********************************************************************
// 处理全局事件
// ********************************************************************
const cxt = getCurrentInstance()
const bus = cxt.appContext.config.globalProperties.$bus
onMounted(() => {
    bus.on('system_main_logout', () => {
        gotoLogin();
        //openTabItem(clickItem)
    })
})

onBeforeUnmount(() => {
    bus.off('system_main_logout')
})
</script>

<style scoped>
.el-dropdown+.el-dropdown {
    margin-left: 15px;
}

.el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}
</style>